package com.oocl.servlet.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.pojo.CartItem;
import com.oocl.pojo.JSONResponse;
import com.oocl.service.CartManager;
import com.oocl.service.impl.CartManagerImpl;


@WebServlet("/reducecartitemcount")
public class ReduceCartItemActionCountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CartManager cartManager = new CartManagerImpl();
    private ObjectMapper mapper = new ObjectMapper();
    private String jsonStr;   

    public ReduceCartItemActionCountServlet() {
        super();
        
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");                      //解决中文乱码
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("content-type","text/html;charset=UTF-8");//解决中文乱码
		Integer code = 1;
		String dId = request.getParameter("did");
		Map<String, CartItem> cart = (Map<String, CartItem>)request.getSession().getAttribute("cart");
		boolean suc = cartManager.reduceCartItemCount(cart, dId);
		request.getSession().setAttribute("cart", cart);
		JSONResponse<CartItem> jsonResponse = new JSONResponse<CartItem>();
		if(suc){
			jsonResponse.setMsg("操作成功!");
		}
		else{
			code=0;
			jsonResponse.setMsg("操作失败!");
		}
		jsonResponse.setCode(code);
		jsonStr = mapper.writeValueAsString(jsonResponse);
		PrintWriter out = response.getWriter();
		out.println(jsonStr);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
